package com.smartcruise.util.network;

import com.smartcruise.BuildConfig;
import com.smartcruise.util.network.netUtils.BaseUrl;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by FengChaoQun
 * on 2016/8/3
 * 所有网络操作统一管理类
 */
public class RetrofitFactory {
    private static final int DEFAULT_TIME = 8;            //默认超时为8s
    private static Retrofit retrofit;
    private static OkHttpClient okHttpClient;
    private static Converter.Factory gsonConverterFactory = GsonConverterFactory.create();
    private static CallAdapter.Factory rxJavaCallAdapterFactory = RxJava2CallAdapterFactory.create();

    public static Retrofit getRetrofit() {
        if (retrofit == null) {
            //添加日志  只在调式版本输出日志
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            //参数拦截器 添加公共参数
            ParamsInterceptor paramsInterceptor = new ParamsInterceptor();
            if (BuildConfig.DEBUG) {
                okHttpClient = new OkHttpClient.Builder()
                        .addInterceptor(paramsInterceptor)
                        .addInterceptor(httpLoggingInterceptor)
                        .connectTimeout(DEFAULT_TIME, TimeUnit.SECONDS)
                        .build();
            } else {
                okHttpClient = new OkHttpClient.Builder()
                        .addInterceptor(paramsInterceptor)
                        .connectTimeout(DEFAULT_TIME, TimeUnit.SECONDS)
                        .build();
            }

            retrofit = new Retrofit.Builder()
                    .client(okHttpClient)
                    .baseUrl(BaseUrl.BASE_URL)
                    .addConverterFactory(gsonConverterFactory)
                    .addCallAdapterFactory(rxJavaCallAdapterFactory)
                    .build();
        }
        return retrofit;
    }
}
